<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/10/30
 * Time: 下午1:50
 */

namespace App\Models;

use App\Models\Configure;
use App\Models\Coupon;
use App\Models\OilCard;
use App\Models\Recharge;
use App\Models\RechargeOrder;
use App\Models\User;
use App\Models\UserCoupon;
use Illuminate\Support\Facades\Validator;
use Modules\Token\Facades\Token;
use Carbon\Carbon;
use EasyWeChat\Factory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;

class Pay extends Model
{
    protected $table = 'pay';

    public $guarded = [];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function rechargeOrder()
    {
        return $this->hasOne(RechargeOrder::class);
    }

    public static function setPaid(Pay $pay)
    {
        try {
            DB::beginTransaction();

            $pay->is_paid = 1;
            $pay->paid_at = Carbon::now()->toDateTimeString();
            $pay->save();
            if ($pay->rechargeOrder) {
                $order          = $pay->rechargeOrder;
                $order->status  = RechargeOrder::STATUS_PAID;
                // 标记已使用
                $useCoupon->status  = UserCoupon::STATUS_USED;
                $useCoupon->used_at = Carbon::now()->toDateTimeString();
                $useCoupon->save();

                $order->paid_at = Carbon::now()->toDateTimeString();
                $order->save();

                // 生成充值明细
                if ($order->type == RechargeOrder::TYPE_RECHARGE) {
                    for ($i = 1; $i <= $order->months; $i++) {
                        if ($i == 1) {
                            $payAt = Carbon::now()->toDateTimeString();
                        } else {
                            $payAt = Carbon::now()->addMonths($i)->toDateTimeString();
                        }

                        $detail = RechargeOrderDetail::create([
                            'recharge_order_id' => $order->id,
                            'current_month'     => $i,
                            'total_month'       => $order->months,
                            'user_id'           => $order->user_id,
                            'oil_card_id'       => $order->oil_card_id,
                            'amount'            => $order->recharge_amount,
                            'pay_at'            => $payAt,
                        ]);

                        // 创建充值任务
                        RechargeTask::createTask($order->oilCard, $detail->amount, $payAt, $order->id, $detail->id);

                    }

                    // 更新用户充值及待充金额
                    $order->user->recharge_amount += (float) ($order->recharge_amount * $order->months);
                    $order->user->pending_amount += (float) ($order->recharge_amount * $order->months);
                    $order->user->save();
                } else {
                    // 创建充值任务
                    $payAt = Carbon::now()->toDateTimeString();
                    RechargeTask::createTask($order->oilCard, $order->recharge_amount, $payAt, $order->id);

                    // 更新用户充值及待充金额
                    $order->user->recharge_amount += (float) ($order->recharge_amount);
                    $order->user->pending_amount += (float) ($order->recharge_amount);
                    $order->user->save();
                }
            }

            DB::commit();

        } catch (\Exception $e) {
            Log::error($e);
            DB::rollBack();
            throw new \Exception('订单支付出错啦');
        }
    }

    public static function alipay(Pay $pay)
    {
        // 创建支付单。
        $alipay = app('alipay.mobile');
        $alipay->setOutTradeNo($pay->pay_sn);
        $alipay->setTotalFee($pay->amount);
        $alipay->setSubject('充值订单');
        $alipay->setBody('充值订单'. $pay->amount . '元');

        // 返回签名后的支付参数给支付宝移动端的SDK。
        return $alipay->getPayPara();
    }

    public static function weixinApp(Pay $pay)
    {
        $app = Factory::payment(config('wechat.app_pay'));
        $result = $app->order->unify([
            'body' => '充值订单'. $pay->amount . '元',
            'out_trade_no' => $pay->pay_sn,
            'total_fee' => $pay->amount * 100,
            'spbill_create_ip' => Request::ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            //'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'APP', // 请对应换成你的支付方式对应的值类型
        ]);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $result = $app->jssdk->appConfig($result['prepay_id']);
        }
        return $result;
    }

    public static function weixin(Pay $pay, $openId)
    {
        $app = Factory::payment(config('wechat.wx_pay'));
        $result = $app->order->unify([
            'body' => '充值订单'. $pay->amount . '元',
            'out_trade_no' => $pay->pay_sn,
            'total_fee' => $pay->amount * 100,
            'spbill_create_ip' => Request::ip(), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            //'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openId,
        ]);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $result = $app->jssdk->bridgeConfig($result['prepay_id']);
        }
        return $result;
    }
}